package com.config;

import com.domain.DomainOne;
import com.repository.DomainOneRepository;
import org.neo4j.driver.AuthTokens;
import org.neo4j.driver.Driver;
import org.neo4j.driver.GraphDatabase;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;
import org.springframework.data.neo4j.config.AbstractNeo4jConfig;
import org.springframework.data.neo4j.config.Neo4jEntityScanner;
import org.springframework.data.neo4j.core.DatabaseSelection;
import org.springframework.data.neo4j.core.DatabaseSelectionProvider;
import org.springframework.data.neo4j.core.UserSelection;
import org.springframework.data.neo4j.core.UserSelectionProvider;
import org.springframework.data.neo4j.core.convert.Neo4jConversions;
import org.springframework.data.neo4j.core.mapping.Neo4jMappingContext;
import org.springframework.data.neo4j.repository.config.EnableNeo4jRepositories;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@Configuration(proxyBeanMethods = false)
@EnableNeo4jRepositories(
        basePackageClasses = DomainOneRepository.class,
        neo4jMappingContextRef = "domain1Context",
        neo4jTemplateRef = "neo4jTemplate",
        transactionManagerRef = "transactionManager"
)
public class Config extends AbstractNeo4jConfig {

    @Autowired
    Environment env;

    @Override
    @Bean
    public Driver driver() {
        return GraphDatabase.driver(env.getRequiredProperty("database1.url"),
                AuthTokens.basic("neo4j", env.getRequiredProperty("database1.password")));
    }

    @Primary @Bean
    public DatabaseSelectionProvider domain1Selection() {
        return () -> DatabaseSelection.byName("neo4j");
    }
    @Primary @Bean
    public UserSelectionProvider userSelection() {
        return () -> UserSelection.impersonate("neo4j");
    }

    @Primary @Bean
    public Neo4jMappingContext domain1Context(Neo4jConversions neo4jConversions) throws ClassNotFoundException {
        Neo4jMappingContext context = new Neo4jMappingContext(neo4jConversions);
        context.setInitialEntitySet(Neo4jEntityScanner.get().scan(DomainOne.class.getPackage().getName()));
        context.setStrict(true);
        return context;
    }


}
